﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Net_SCADA;

namespace WZXC_GBL_QUERY
{
    public partial class Form_DataBackup : Form
    {
        private DateTime _StartDate=DateTime.Now.Date;
        private DateTime _EndDate=DateTime.Now.Date;
        private Form_Query _fmquery;
        public Form_DataBackup(Form_Query fmquery)
        {
            _fmquery = fmquery;
            InitializeComponent();
        }

        private void Form_DataBackup_Load(object sender , EventArgs e)
        {
            txt_Folder.Text = Application.StartupPath;
            dtp_DayEnd.Value = dtp_DayStart.Value = DateTime.Now.Date;
        }

        private void btn_Cancel_Click(object sender , EventArgs e)
        {
            _fmquery.Show();
            Application.DoEvents();
            this.Dispose();
        }

        private void btn_Browser_Click(object sender , EventArgs e)
        {
            FolderDialog.SelectedPath = Application.StartupPath;
            if (FolderDialog.ShowDialog() == DialogResult.OK)
            {
                txt_Folder.Text = FolderDialog.SelectedPath;
            }
        }
        #region fileoperate
        private void WriteEventFile(DataTable dt,StringBuilder file)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                StringBuilder sb=new StringBuilder("序号,事件时间,事件类型,事件对象,操作人员,原始数据,新数据");
                sb.AppendLine();
                for (int i = 0 ; i < dt.Rows.Count ; i++)
                {
                    sb.Append(i + 1).Append(",")
                      .Append(dt.Rows[i]["savetime"]).Append(",")
                      .Append(dt.Rows[i]["action"]).Append(",")
                      .Append(dt.Rows[i]["target"]).Append(",")
                      .Append(dt.Rows[i]["user"]).Append(",")
                      .Append(dt.Rows[i]["oldvalue"].ToString().Replace(',' , '_')).Append(",")
                      .Append(dt.Rows[i]["newvalue"].ToString().Replace(',' , '_'));
                    sb.AppendLine();
                }
                SaveDataToFile(sb , file);
            }
        }
        private void WriteBatchFile(DataTable dt , StringBuilder file)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                StringBuilder sb=new StringBuilder("序号,批次编号,创建用户,创建时间,停止时间,结束时间,产品编号");
                sb.AppendLine();
                for (int i = 0 ; i < dt.Rows.Count ; i++)
                {
                    sb.Append(i+1).Append(",")
                      .Append(dt.Rows[i]["batchserial"]).Append(",")
                      .Append(dt.Rows[i]["createuser"]).Append(",")
                      .Append(dt.Rows[i]["createtime"]).Append(",")
                      .Append(dt.Rows[i]["stoptime"]).Append(",")
                      .Append(dt.Rows[i]["endtime"]).Append(",")
                      .Append(dt.Rows[i]["productversion"]);
                    sb.AppendLine();
                    Application.DoEvents();
                }
                SaveDataToFile(sb , file);
            }
        }
        private void WriteAlarmFile(DataTable dt,StringBuilder file)
        {
            if(dt!=null && dt.Rows.Count > 0)
            {
                StringBuilder sb=new StringBuilder("时间,警报名称,警报动作,等级,编号");
                sb.AppendLine();
                for (int i = 0 ; i < dt.Rows.Count ; i++)
                {
                    sb.Append(dt.Rows[i]["SaveTime"]).Append(",")
                        .Append(dt.Rows[i]["AlarmName"]).Append(",")
                        .Append(dt.Rows[i]["AlarmActive"].ToString() == "1" ? "发生" : "消除").Append(",")
                        .Append(dt.Rows[i]["AlarmLevel"]).Append(",")
                        .Append(dt.Rows[i]["AlarmID"]);
                    sb.AppendLine();
                    Application.DoEvents();

                }
                SaveDataToFile(sb , file);
            }
        }
        private void WriteDayFile(DataTable dt , StringBuilder file)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                StringBuilder sb=new StringBuilder("时间,");
                foreach (var i in QueryForms.fmquery.netline.zone.Keys)
                {
                    if (QueryForms.fmquery.netline.zone[i].pv != null) sb.Append(QueryForms.fmquery.netline.zone[i].ZoneName).Append("-PV,");
                    if (QueryForms.fmquery.netline.zone[i].sv != null) sb.Append(QueryForms.fmquery.netline.zone[i].ZoneName).Append("-SV,");
                    if (QueryForms.fmquery.netline.zone[i].ovpv != null) sb.Append(QueryForms.fmquery.netline.zone[i].ZoneName).Append("-OverPV,");
                }
                sb.AppendLine();
                for (int i = 0 ; i < dt.Rows.Count ; i++)
                {
                    sb.Append(dt.Rows[i]["SaveTime"].ToString()).Append(",");
                    foreach (var j in QueryForms.fmquery.netline.zone.Keys)
                    {
                        if (QueryForms.fmquery.netline.zone[j].pv != null)
                           sb.Append(getDataFromDatatable(dt, i, QueryForms.fmquery.netline.zone[j].pv.ID.ToString()));
                        if (QueryForms.fmquery.netline.zone[j].sv != null) 
                           sb.Append(getDataFromDatatable(dt, i, QueryForms.fmquery.netline.zone[j].sv.ID.ToString()));
                        if (QueryForms.fmquery.netline.zone[j].ovpv != null) 
                           sb.Append(getDataFromDatatable(dt, i, QueryForms.fmquery.netline.zone[j].ovpv.ID.ToString()));
                    }
                    sb.AppendLine();
                    Application.DoEvents();
                }
                SaveDataToFile(sb , file);
            }
        }
        private StringBuilder getDataFromDatatable(DataTable dt,int rowindex, string colname)
        {
            StringBuilder sb = new StringBuilder();
            if (dt.Columns.Contains(colname))
                sb.Append(dt.Rows[rowindex][colname]);
            sb.Append(",");
            return sb;
        }
        private void WriteBoxFile(DataTable dt , StringBuilder file)
        {
           //需要对文件头进行解析

            if (dt != null && dt.Rows.Count > 0)
            {
                DateTime dt1,dt2; TimeSpan ts;
                StringBuilder sb=new StringBuilder("序号,料框编号,批次编号,创建用户,装料时间,产品名称,淬火转移时间,加热炉总时间,");

                for (int i = 0 ; i < QueryForms.fmquery.netline.BoxKeyTime.Count ; i++)
                {
                    sb.Append(QueryForms.fmquery.netline.BoxKeyTime[i].KeyTimeName).Append("进入时间,").Append(QueryForms.fmquery.netline.BoxKeyTime[i].KeyTimeName).Append("移出时间,").Append(QueryForms.fmquery.netline.BoxKeyTime[i].KeyTimeName).Append("总时间,");
                }
                sb.AppendLine();

                for (int i = 0 ; i < dt.Rows.Count ; i++)
                {
                    //添加前置信息
                    sb.Append(i).Append(",");
                    sb.Append(dt.Rows[i]["box"].ToString()).Append(",")
                        .Append(dt.Rows[i]["batchserial"].ToString()).Append(",")
                        .Append(dt.Rows[i]["createuser"].ToString()).Append(",")
                        .Append(dt.Rows[i]["loadtime"].ToString()).Append(",")
                        .Append(dt.Rows[i]["info0"].ToString()).Append(",")
                        .Append(dt.Rows[i]["quenchmoveintime"].ToString()).Append(",");

                    if(DateTime.TryParse(dt.Rows[i]["keytime13"].ToString(),out dt1) && DateTime.TryParse(dt.Rows[i]["keytime9"].ToString(),out dt2))
                    {
                        ts = dt1.Subtract(dt2);
                        sb.Append(ts.Hours.ToString()).Append(":").Append(ts.Minutes).Append(":").Append(ts.Seconds).Append(",");
                    }
                    else
                        sb.Append("-,");
                    //添加时间信息
                    for (int j = 0 ; j < QueryForms.fmquery.netline.BoxKeyTime.Count ; j++)
                    {
                        DateTime.TryParse(dt.Rows[i]["keytime" + QueryForms.fmquery.netline.BoxKeyTime[j].KeyTimeInIndex].ToString() , out dt1);
                        DateTime.TryParse(dt.Rows[i]["keytime" + QueryForms.fmquery.netline.BoxKeyTime[j].KeyTimeOutIndex].ToString() , out dt2);
                        bool isok1 = !( dt1.Year < 2021);
                        sb.Append(isok1 ? dt1.ToString("yyyy-MM-dd HH:mm:ss") : "-").Append(",");
                        bool isok2 =!(dt2.Year < 2021);
                        sb.Append(isok2 ? dt2.ToString("yyyy-MM-dd HH:mm:ss") : "-").Append(",");
                        if (isok1 && isok2)
                        {
                            ts= dt2.Subtract(dt1);
                            sb.Append(ts.Hours.ToString()).Append(":").Append(ts.Minutes).Append(":").Append(ts.Seconds).Append(",");
                        }
                        else
                            sb.Append( "-,");
                        Application.DoEvents();
                    }
                    sb.AppendLine();
                }
                SaveDataToFile(sb , file);
            }
        }
        private void WriteProductInfo(StringBuilder file)
        {
            DataTable dtProduct=DBOperate.GetProductInfo();
            if(dtProduct != null && dtProduct.Rows.Count > 0)
            {
                Dictionary<string,string> title=new Dictionary<string, string>();
                DataTable dtInfoTitle=DBOperate.GetProductInfoTitle();
                if(dtInfoTitle != null && dtInfoTitle.Rows.Count > 0)
                {
                    for (int i = 0 ; i < dtInfoTitle.Rows.Count ; i++)
                    {
                        title["info" + dtInfoTitle.Rows[i]["infoID"]] = dtInfoTitle.Rows[i]["infoTitle"].ToString();
                    }
                }
                title["keyalarm"] = "位置报警";
                title["lampalarm"] = "亮灯报警";
                StringBuilder sb=new StringBuilder("产品编号,保存时间,");
                foreach (var i in title.Keys)
                {
                    sb.Append(title[i]).Append(",");
                }
                sb.AppendLine();
                for (int i = 0 ; i < dtProduct.Rows.Count ; i++)
                {
                    sb.Append(dtProduct.Rows[i]["ProductVersion"]).Append(",")
                        .Append(dtProduct.Rows[i]["SaveTime"]).Append(",");
                    foreach (var item in title.Keys)
                    {
                        sb.Append(dtProduct.Rows[i][item]).Append(",");
                        Application.DoEvents();
                    }
                    sb.AppendLine();
                }
                SaveDataToFile(sb , file);

            }

        }
        private void WriteProductProgram(StringBuilder file)
        {
            DataTable dtProgram=DBOperate.GetProductProgram();

            if (dtProgram != null && dtProgram.Rows.Count > 0)
            {

                DataTable dtSetpoint=DBOperate.GetSetPointSet();
                Dictionary<string,string> setpoint=new Dictionary<string, string>();
                if (dtSetpoint != null && dtSetpoint.Rows.Count > 0)
                {
                    for (int i = 0 ; i < dtSetpoint.Rows.Count ; i++)
                    {
                        setpoint[dtSetpoint.Rows[i]["ZoneID"].ToString()] = dtSetpoint.Rows[i]["ZoneName"].ToString();
                    }

                }

                StringBuilder sb=new StringBuilder("产品编号,创建时间,最后修改时间,");

                foreach (var item in setpoint.Keys)
                {
                    sb.Append(setpoint[item]).Append(",");
                }
                sb.AppendLine();
                for (int i = 0 ; i < dtProgram.Rows.Count ; i++)
                {
                    try
                    {
                        sb.Append(dtProgram.Rows[i]["ProductVersion"]).Append(",")
                                .Append(dtProgram.Rows[i]["CreateTime"]).Append(",")
                                .Append(dtProgram.Rows[i]["LastModifyTime"]).Append(",");
                        foreach (var item in setpoint.Keys)
                        {
                            sb.Append(dtProgram.Rows[i][item]).Append(",");
                        }
                    }
                    catch (Exception)
                    {
                        sb.AppendLine();
                        continue;
                    }
                    sb.AppendLine();
                    Application.DoEvents();
                }
                SaveDataToFile(sb , file);
            }
        }
        private void WriteSettings(DataTable dt,StringBuilder file )
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                StringBuilder sb=new StringBuilder();
                for (int i = 0 ; i < dt.Columns.Count ; i++)
                {
                    sb.Append(dt.Columns[i].ColumnName).Append(",");
                }
                sb.AppendLine();
                for (int i = 0 ; i < dt.Rows.Count ; i++)
                {
                    for (int j = 0 ; j < dt.Columns.Count ; j++)
                    {
                        sb.Append(dt.Rows[i][j].ToString().Replace(',','_')).Append(",");
                    }
                    sb.AppendLine();
                }
                SaveDataToFile(sb , file);
            }
        }
        private void SaveDataToFile(StringBuilder sb , StringBuilder file)
        {
            // FileStream fs = new FileStream(file.ToString(), FileMode.Create);
            StreamWriter sw = new StreamWriter(file.ToString(),true, Encoding.GetEncoding(936));
            sw.Write(sb);  //这里是写入的内容             
            sw.Flush();
            sw.Close();
        }
        #endregion
        private void btn_BackupConfirm_Click(object sender , EventArgs e)
        {
            //创建文件夹  BackupData20210623
            StringBuilder sbdir=new StringBuilder(txt_Folder.Text).Append("\\RecordData") .Append(DateTime.Now.ToString("yyyyMMdd"));
            if(!Directory.Exists(sbdir.ToString())) Directory.CreateDirectory(sbdir.ToString());
            pnl_backup.Visible = true;

            if (_StartDate > _EndDate) { DateTime dtime=_EndDate;_EndDate = _StartDate;_StartDate = dtime; dtp_DayStart.Value = _StartDate;dtp_DayEnd.Value = _EndDate; }
            int totaldays=(int)_EndDate.Subtract(_StartDate).TotalDays+1;
            DataTable dt=new DataTable(); StringBuilder sbsubdir; StringBuilder sbFilename;
            for (int i = 0 ; i < totaldays ; i++)
            {
                lbl_ActionInfo.Text = "正在导出" + _StartDate.AddDays(i).ToString("yyyy年MM月dd日") + "相关数据";
                if (chk_HisData.Checked)//历史数据
                {
                    //1  Day
                    sbsubdir = new StringBuilder().Append(sbdir).Append("\\Day");
                    if (!Directory.Exists(sbsubdir.ToString())) Directory.CreateDirectory(sbsubdir.ToString());
                    dt = DBOperate.GetParameterData(_StartDate.AddDays(i) , _StartDate.AddDays(i + 1).Date.AddSeconds(-1));
                    sbFilename = new StringBuilder().Append(sbsubdir.ToString()).Append("\\his_day").Append(_StartDate.AddDays(i).ToString("yyyyMMdd")).Append(".csv");
                    WriteDayFile(dt , sbFilename);

                    //2  batch
                    sbsubdir = new StringBuilder().Append(sbdir).Append("\\Batch");
                    if (!Directory.Exists(sbsubdir.ToString())) Directory.CreateDirectory(sbsubdir.ToString());
                    dt = DBOperate.GetBatchByTime(_StartDate.AddDays(i) , _StartDate.AddDays(i + 1).Date.AddSeconds(-1));
                    sbFilename = new StringBuilder().Append(sbsubdir.ToString()).Append("\\his_batch").Append(_StartDate.AddDays(i).ToString("yyyyMMdd")).Append(".csv");
                    WriteBatchFile(dt , sbFilename);

                    //3  box
                    sbsubdir = new StringBuilder().Append(sbdir).Append("\\Box");
                    if (!Directory.Exists(sbsubdir.ToString())) Directory.CreateDirectory(sbsubdir.ToString());
                    dt = DBOperate.GetProcessBoxByTime(_StartDate.AddDays(i) , _StartDate.AddDays(i + 1).Date.AddSeconds(-1));
                    sbFilename = new StringBuilder().Append(sbsubdir.ToString()).Append("\\his_box").Append(_StartDate.AddDays(i).ToString("yyyyMMdd")).Append(".csv");
                    WriteBoxFile(dt , sbFilename);

                    //4 报警数据
                    sbsubdir = new StringBuilder().Append(sbdir).Append("\\Alarm");
                    if (!Directory.Exists(sbsubdir.ToString())) Directory.CreateDirectory(sbsubdir.ToString());
                    dt = DBOperate.GetAlarmHistory(_StartDate.AddDays(i) , _StartDate.AddDays(i + 1));
                    sbFilename = new StringBuilder().Append(sbsubdir.ToString()).Append("\\his_alarm").Append(_StartDate.AddDays(i).ToString("yyyyMMdd")).Append(".csv");
                    WriteAlarmFile(dt , sbFilename);

                    //5  event
                    sbsubdir = new StringBuilder().Append(sbdir).Append("\\Event");
                    if (!Directory.Exists(sbsubdir.ToString())) Directory.CreateDirectory(sbsubdir.ToString());
                    dt = DBOperate.GetEventByTime(_StartDate.AddDays(i) , _StartDate.AddDays(i + 1).Date.AddSeconds(-1));
                    sbFilename = new StringBuilder().Append(sbsubdir.ToString()).Append("\\his_event").Append(_StartDate.AddDays(i).ToString("yyyyMMdd")).Append(".csv");
                    WriteEventFile(dt , sbFilename);
                }
            }
            if (chk_ProgramData.Checked)//工艺数据
            {
                lbl_ActionInfo.Text = "正在导出工艺相关数据";
                Application.DoEvents();
                //产品信息
                sbsubdir = new StringBuilder().Append(sbdir).Append("\\Program");
                if (!Directory.Exists(sbsubdir.ToString())) Directory.CreateDirectory(sbsubdir.ToString());
                sbFilename = new StringBuilder().Append(sbsubdir.ToString()).Append("\\pro_productinfo.csv");
                WriteProductInfo(sbFilename);

                //工艺内容
                sbFilename = new StringBuilder().Append(sbsubdir.ToString()).Append("\\pro_productprogram.csv");
                WriteProductProgram(sbFilename);
            }
            if (chk_SettingData.Checked)//设置参数
            {
                lbl_ActionInfo.Text = "正在导出相关设置数据";
                Application.DoEvents();
                sbsubdir = new StringBuilder().Append(sbdir).Append("\\Settings");
                if (!Directory.Exists(sbsubdir.ToString())) Directory.CreateDirectory(sbsubdir.ToString());
                //alarm color
                sbFilename = new StringBuilder().Append(sbsubdir.ToString()).Append("\\set_alarm_color.csv");
                dt = DBOperate.GetAlarmLevelColorSet();
                WriteSettings(dt , sbFilename);
                //alarm set
                sbFilename = new StringBuilder().Append(sbsubdir.ToString()).Append("\\set_alarm_siemens.csv");
                dt = DBOperate.GetAlarmSet();
                WriteSettings(dt , sbFilename);
                //set_designgroup
                sbFilename = new StringBuilder().Append(sbsubdir.ToString()).Append("\\set_designgroup.csv");
                dt = DBOperate.GetDesignGroupSet();
                WriteSettings(dt , sbFilename);
                //set_designgroup
                sbFilename = new StringBuilder().Append(sbsubdir.ToString()).Append("\\set_equip.csv");
                dt = DBOperate.GetEquipSet();
                WriteSettings(dt , sbFilename);
                //set_item_siemens
                sbFilename = new StringBuilder().Append(sbsubdir.ToString()).Append("\\set_item_siemens.csv");
                dt = DBOperate.GetItemSet();
                WriteSettings(dt , sbFilename);
                //set_keytime
                sbFilename = new StringBuilder().Append(sbsubdir.ToString()).Append("\\set_keytime.csv");
                dt = DBOperate.GetKeyTimeSet();
                WriteSettings(dt , sbFilename);
                //set_productinfotitle
                sbFilename = new StringBuilder().Append(sbsubdir.ToString()).Append("\\set_productinfotitle.csv");
                dt = DBOperate.GetProductInfoTitle();
                WriteSettings(dt , sbFilename);
                //set_setpoint_siemens
                sbFilename = new StringBuilder().Append(sbsubdir.ToString()).Append("\\set_setpoint_siemens.csv");
                dt = DBOperate.GetSetPointSet();
                WriteSettings(dt , sbFilename);
                //set_zone
                sbFilename = new StringBuilder().Append(sbsubdir.ToString()).Append("\\set_zone.csv");
                dt = DBOperate.GetZoneSet();
                WriteSettings(dt , sbFilename);
            }
            pnl_backup.Visible = false;
            dt.Clear();
            dt = null;
        }

        private void dtp_DayStart_ValueChanged(object sender , EventArgs e)
        {
            _StartDate = dtp_DayStart.Value;
        }

        private void dtp_DayEnd_ValueChanged(object sender , EventArgs e)
        {
            _EndDate = dtp_DayEnd.Value;
        }
    }
}
